﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormZhangYiDa
{
    using log4net;
    using System.Xml;

    public  class Log4NetHelper
    {
        private static  string M_logFile;

        private static  Dictionary<string, log4net.ILog> m_lstog = new Dictionary<string, ILog>();

        public static void InitLog4Net(string strLog4NetConfigFile) {

            log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(strLog4NetConfigFile));
            M_logFile = strLog4NetConfigFile;
            m_lstog["info_log"] = log4net.LogManager.GetLogger("info_log");
            m_lstog["error_log"] = log4net.LogManager.GetLogger("error_log");
        }
        /// <summary>
        /// 写入日志信息
        /// </summary>
        /// <param name="strInfoLog"></param>
        public static void WriteInfo(string strInfoLog) {

            if (m_lstog["info_log"].IsInfoEnabled) {

                m_lstog["info_log"].Info(strInfoLog);
               
            }
        }


        /// <summary>
        /// 写入错误日志信息
        /// </summary>
        /// <param name="strInfoLog"></param>
        public static void WriteError(string strerrorLog)
        {

            if (m_lstog["error_log"].IsErrorEnabled)
            {

                m_lstog["error_log"].Error(strerrorLog);
             
            }
        }
        /// <summary>
        ///  功能描述:写入日志
        /// </summary>
        /// <param name="strType"></param>
        /// <param name="strLog"></param>
        public static void WriteByLogType(string strType, string strLog) {

            if (!m_lstog.ContainsKey(strType)) {

                if (!HasLogNode(strType)) {

                    WriteError("log4net配置文件不存在【" + strType + "】配置");
                    return;
                }
                m_lstog[strType] = log4net.LogManager.GetLogger(strType);
            }
            m_lstog[strType].Error(strLog);

        }
        /// <summary>
        /// 功能描述:是否存在指定的配置
        /// </summary>
        /// <param name="strNodeName">strNodeName</param>
        /// <returns>返回值</returns>
        private static bool HasLogNode(string strNodeName)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(M_logFile);
         
            var lstNodes = doc.SelectNodes("//configuration/log4net/logger");
            foreach (XmlNode item in lstNodes)
            {
                if (item.Attributes["name"].Value.ToLower() == strNodeName)
                    return true;
            }
            return false;
        }
    }
}
